package 二分查找;

public class 二分查找1 {
    //https://leetcode.cn/problems/binary-search/description/
    public int search1 (int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid = (left + right) / 2;
        while (left <= right) {
            if (nums[mid] > target) {
                right = mid - 1;
            }else if(nums[mid] < target) {
                left = mid + 1;
            }else {
                return mid;
            }
            mid = (left + right) / 2;
        }
        return -1;
    }
    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while(left <= right) {
            //int mid = (left + right) / 2; // 如果两个大数相加 就会和溢出算数范围，所以相加时得一方是确保小数
            int mid = left + (right - left) / 2; // 一方小数求中点(算术和为mid 比right小 都没有溢出)
            if(nums[mid] > target) right = mid - 1;
            else if(nums[mid] < target) left = mid + 1;
            else return mid;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = new int[] {-1,0,3,5,9,12};
        int target = 13;
        search(nums,target);
    }
}
